package drds.datasource.connection_pool.checker;

import drds.datasource.connection_pool.util.JdbcUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
public class ConnectionValidCheckerImpl implements ConnectionValidChecker {

    public static final String DEFAULT_VALIDATION_QUERY = "SELECT 1";


    public boolean isValid(Connection connection, String validateQuery, int validationQueryTimeout)
            throws SQLException {
        if (connection.isClosed()) {
            return false;
        }


        if (validateQuery == null || validateQuery.isEmpty()) {
            validateQuery = DEFAULT_VALIDATION_QUERY;
        }

        Statement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.createStatement();
            if (validationQueryTimeout > 0) {
                statement.setQueryTimeout(validationQueryTimeout);
            }
            resultSet = statement.executeQuery(validateQuery);
            return true;
        } finally {
            JdbcUtils.close(resultSet);
            JdbcUtils.close(statement);
        }

    }

}
